(function(win,$){
	var userId= getQueryParamValue("userId");
	$(document).ready(function(){
		//判断是否为车主
		$.ajax({
			headers: {'Cookie' : document.cookie },
			method : 'get',
			url : rootPath+'/customer/api/v1/queryUserOwner',
			error:function(XMLHttpRequest, ajaxOptions, thrownError){
				//alert("数据刷新失败");
			},
			success : function(resultData){
				if(resultData.length==0){
					//不是会员
					alert("请先注册成会员");
					window.location = rootPath + "/views/homepage/signUp.html";
				}else{
					//是会员
				}
			}
		});
		
		
		/*去掉iphone手机滑动默认行为*/
//		$('body').on('touchmove', function (event) {
//		    event.preventDefault();
//		});
		var rootPath = getRootPath();
		var dealerCode= getQueryParamValue("dealerCode");
		
//		$("#nowDealerDiv").hide();
//		$("#maintainDealerDiv").hide();
//		$("#level2").hide();
//		$("#level3").hide();
		//监听城市选择页面搜索输入框
		$("#cha").keyup(function(event){ 
	        if (event.keyCode === 13){ 
	       	 searchCity();
	        } 
	      }); 
		
		//监听经销商选择页面搜索输入框
		$("#sou").keyup(function(event){ 
	        if (event.keyCode === 13){ 
	       	 searchDealer();
	        } 
	      }); 

	})

	function addCarInfo(){
		$("#level1").hide();
		$("#level2").show();
	}
	function next(){
		//2017-04-07   liyh1  添加加载层 并  灰色按钮
		layer.load(1,{shade:false});
		$("#next").attr("disabled","disabled");
		$("#next").attr("class","btnbtn1");
		$("#next").removeAttr("style");
		var carInfoDto = {
				"vin": $("#vin").val(),
				"engine": $("#engineNo").val(),
				"userId": userId
		}
		//alert(carInfoDto.vin+','+carInfoDto.engineNo);
		$.ajax({
			headers: {'Cookie' : document.cookie },
			type : "POST",
			url : rootPath + "/customer/api/v1/carInfo",
			dataType : "json",
			contentType : "application/json",
			data : JSON.stringify(carInfoDto),
			success : function(resultDate) {
	        	var datas=eval(resultDate);
	        	alert(datas.resultCode);
	        	if(datas.resultCode=='绑定成功！'){
	        		//获取默认经销商信息
	        		$.ajax({
	        			headers: {'Cookie' : document.cookie },
	        			method : 'get',
	        			url : rootPath+'/customer/api/v1/dealerInfo?latitude='+$("#latitude").val()+'&longitude='+$("#longitude").val(),
	        	        dataType:"json",      
	        	        async: false,
	        	        contentType:"application/json",               
	        	        data:null, 
	        			error:function(XMLHttpRequest, ajaxOptions, thrownError){
	        				alert("获取默认销售店信息失败!");
	        			},
	        			success : function(resultData){
	        				$.each(resultData,function(maintainSelIndex,maintainSelObj){
	        					$("#dealerCode").val(maintainSelObj.dealerCode);
	        					//var dealerName = maintainSelObj.dealerShortName;
	        					//var detailAddress = maintainSelObj.detailAddress;
	        					$("#dealerName").html(maintainSelObj.dealerShortName);
	        					$("#detailAddress").html(maintainSelObj.detailAddress);
	        					
	        				});
	        			}
	        		});
					//window.location = rootPath + "/views/hpp.html";
	    			$("#level2").hide();
	    			$("#level3").show();
	    			layer.closeAll('loading');
	        	}else{
	        		//location.reload();
	        		$("#next").removeAttr("disabled");
	        		$("#next").attr("class","btnbtn");
	        		layer.closeAll('loading');
	        	}
			},
			error : function(data) {
				//alert("认证失败！");
			}
		});
		layer.closeAll('loading');
	}
	//定位所在地经销商,点击
	function selectNowDealer(obj){
		 $("#headImg").hide();
		 $("#sou").val("");
		 $("#firstImg").hide();
		 $("#maintainDealerDiv").hide();
		 $("#maintainDealerDiv").removeClass("active in");
		 $("#level3").hide();
		 $("#nowDealerDiv").show();
		 $("#dealerDiv").html("");
		 //初始化界面
		 $("#nowDealerDiv").addClass("active in");
			//根据编号获取所在地经销商列表
				$.ajax({
					headers: {'Cookie' : document.cookie },
					method : 'get',
					url : rootPath+'/maintain/api/v1/maintainDealer?regionName='+ $("#regionName").val()+'&dealerCode='+dealerCode,
					error:function(XMLHttpRequest, ajaxOptions, thrownError){
						//alert("未连接服务器!");
					},
					success : function(resultData){
						var wholeHtml = '';
						var  Km = '';
						$.each(resultData,function(maintainDealerIndex,maintainDealerObj){
							
							var findDealerHtml = '';
							var lat1 = maintainDealerObj.latitude;
							var lng1 = maintainDealerObj.longitude;
							var lat2 = $("#latitude").val();
							var lng2 = $("#longitude").val();
							Km = GetDistance(lat1,lng1,lat2,lng2).toFixed(2);
							if(lat1==null||lat1=="0"||lng1==null||lng1=="0"){var distance = "暂无";}
							else{var distance = Km + '千米';}
							
								if(maintainDealerObj.remark =='首选店'){
									$("#nameFirst").html(maintainDealerObj.dealerName);
									$("#distanceFirst").html(distance);
									$("#addrFirst").html(maintainDealerObj.detailAddress);
									$("#codeFirst").val(maintainDealerObj.dealerCode);
									$('#Tel').attr('href',maintainDealerObj.serviceHotline);
									$("#remarkFirst").html(maintainDealerObj.remark);
								}else{
									$("#KmFirst").hide();
							findDealerHtml = findDealerHtml + '<li data-id="'+ Km +'">'
															+ '<div class="panel panel-default">'
															+ '<table style="width:100%" class="table-condensed"><tbody>'
															+ '<tr>'
															+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+maintainDealerIndex+')">'
															+ '<p id="name'+ maintainDealerIndex +'" style="font-family:黑体;font-size:16px;color:#000000">' + maintainDealerObj.dealerName + '</p>'
															+ '<p class="hidden" id="shortName'+maintainDealerIndex+'">'+maintainDealerObj.dealerShortName+'</p>'
															+ '</a></td>'
															+ '<td style="width:100px;text-align:center;font-size:14px;color:#7a7a7a">'
															+ '<span>距离：</span><span>'+ distance + '</span>'
															+ '</td>'
															+ '</tr><tr>'
															+ '<td style="width:160px;text-align:left;">'
															+ '<span id="addr'+ maintainDealerIndex +'" style="font-faminly:宋体;font-size:15px;color:#615f5f">' + maintainDealerObj.detailAddress + '</span>'
															+ '</td>'
															+ '<td style="width:100px;text-align:center;">'
															+ '<a href="tel:'+ maintainDealerObj.serviceHotline +'" id="Tel">'
															+ '<span class="glyphicon glyphicon-earphone" style="color: rgb(255, 0, 23); font-size: 12px;"></span>'
															+ '<span style="font-family:宋体;font-size:14px;color:#7a7a7a"> 电话</span>'
															+ '</a></td>'
															+ '</tr>'
															+ '</tbody></table>'
															+ '<input id="code'+ maintainDealerIndex +'" class="hidden" value="' + maintainDealerObj.dealerCode + '">'
															+ '</div></li>'
							
							wholeHtml += findDealerHtml;
							}
						});
						$("#dealerDiv").append(wholeHtml);
					}
				});
	}
	function sureDealer(obj){
		if(obj=='-1'){
			  var code = $("#codeFirst").val();
		 	  var name = $("#shortNameFirst").html();
		   	  var addr = $("#addrFirst").html();
			}else{
			  var code = $("#code"+obj).val();
			  var name = $("#shortName"+obj).html();
			  var addr = $("#addr"+obj).html();
			}
		//alert(code+','+name+','+addr);
		$("#dealerCode").val(code);
		$("#dealerName").html(name);
		$("#detailAddress").html(addr);
		$("#nowDealerDiv").hide();
		$("#nowDealerDiv").removeClass("active in");
		 $("#level3").show();
		 $("#headImg").show();
		 $("#list2").show();
		 $("#searchDealer").html("");
		 var dealerDto = {"dealerCode":$("#dealerCode").val()}
		 $.ajax({
				headers: {'Cookie' : document.cookie },
				type : "POST",
				url : rootPath + "/customer/api/v1/dealerCode",
				dataType : "json",
				contentType : "application/json",
				data : JSON.stringify(dealerDto),
				success : function(resultDate) {
				},
				error : function(data) {
				}
			});
	}
	//排序
	function Sort(bo)
	{
	    var arr = document.getElementById("list2").innerHTML.match(/<li>[\s\S]+?<\/li>/g);
	    arr.sort(function(a,b){
	        a = parseInt(/\d+/.exec(a)[0], 10);
	        b = parseInt(/\d+/.exec(b)[0], 10);
	        return bo?b-a:a-b;
	    });
	    document.getElementById("ol1").innerHTML = arr.join("");
	}
	//进行经纬度转换为距离的计算

	function Rad(d){
	  return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
	}
	//计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
	function GetDistance(lat1,lng1,lat2,lng2){

	   var radLat1 = Rad(lat1);
	   var radLat2 = Rad(lat2);
	   var a = radLat1 - radLat2;
	   var  b = Rad(lng1) - Rad(lng2);
	   var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
	   Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
	   s = s *6378.137 ;// EARTH_RADIUS;
	   s = Math.round(s * 10000) / 10000; //输出为公里
	   //s=s.toFixed(4);
	   return s;
	}
	function selectDealer(obj){
		$("#sou").val("");
		$("#headImg").hide();
		var code = $("#"+obj).val();
		$("#regionName").val(code);
		$("#maintainDealerDiv").hide();
		$("#maintainDealerDiv").removeClass("active in");
		$("#dealerDiv").html("");
		 $("#nowDealerDiv").show();
		 $("#searchCity").html("");
		 $("#searchDealer").html("");
		 $("#list2").show();
		 //初始化界面
		 $("#nowDealerDiv").addClass("active in");
		 for(var i=0;i<26;i++){
				var en = String.fromCharCode((65+i));
				$("#"+en).html("");
		 }
		//根据编号获取所在地经销商列表
		$.ajax({
			headers: {'Cookie' : document.cookie },
			method : 'get',
			url : rootPath+'/maintain/api/v1/maintainDealer?regionName='+code+'&dealerCode='+dealerCode,
			error:function(XMLHttpRequest, ajaxOptions, thrownError){
				//alert("未连接服务器!");
			},
			success : function(resultData){
				
				var wholeHtml = '';
				var  Km = '';
				$.each(resultData,function(maintainDealerIndex,maintainDealerObj){
					
					var findDealerHtml = '';
					var lat1 = maintainDealerObj.latitude;
					var lng1 = maintainDealerObj.longitude;
					var lat2 = $("#latitude").val();
					var lng2 = $("#longitude").val();
					Km = GetDistance(lat1,lng1,lat2,lng2).toFixed(2);
					if(lat1==null||lat1=="0"||lng1==null||lng1=="0"){var distance = "暂无";}
					else{var distance = Km + '千米';}
					
						if(maintainDealerObj.remark =='首选店'){
							$("#nameFirst").html(maintainDealerObj.dealerName);
							$("#distanceFirst").html(distance);
							$("#addrFirst").html(maintainDealerObj.detailAddress);
							$("#codeFirst").val(maintainDealerObj.dealerCode);
							$('#Tel').attr('href',maintainDealerObj.serviceHotline);
							$("#remarkFirst").html(maintainDealerObj.remark);
						}else{
							$("#KmFirst").hide();
					findDealerHtml = findDealerHtml + '<li data-id="'+ Km +'">'
													+ '<div class="panel panel-default">'
													+ '<table style="width:100%" class="table-condensed"><tbody>'
													+ '<tr>'
													+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+maintainDealerIndex+')">'
													+ '<p id="name'+ maintainDealerIndex +'" style="font-family:黑体;font-size:16px;color:#000000">' + maintainDealerObj.dealerName + '</p>'
													+ '<p class="hidden" id="shortName'+maintainDealerIndex+'">'+maintainDealerObj.dealerShortName+'</p>'
													+ '</a></td>'
													+ '<td style="width:100px;text-align:center;font-size:14px;color:#7a7a7a">'
													+ '<span>距离：</span><span>'+ distance + '</span>'
													+ '</td>'
													+ '</tr><tr>'
													+ '<td style="width:160px;text-align:left;">'
													+ '<span id="addr'+ maintainDealerIndex +'" style="font-faminly:宋体;font-size:15px;color:#615f5f">' + maintainDealerObj.detailAddress + '</span>'
													+ '</td>'
													+ '<td style="width:100px;text-align:center;">'
													+ '<a href="tel:'+ maintainDealerObj.serviceHotline +'" id="Tel">'
													+ '<span class="glyphicon glyphicon-earphone" style="color: rgb(255, 0, 23); font-size: 12px;"></span>'
													+ '<span style="font-family:宋体;font-size:14px;color:#7a7a7a"> 电话</span>'
													+ '</a></td>'
													+ '</tr>'
													+ '</tbody></table>'
													+ '<input id="code'+ maintainDealerIndex +'" class="hidden" value="' + maintainDealerObj.dealerCode + '">'
													+ '</div></li>'
					
					wholeHtml += findDealerHtml;
					}
				});
				$("#dealerDiv").append(wholeHtml);
			}
		});
	}
	//选择经销商，点击
	function selectMaintainDealer(obj){
		$("#headImg").hide();
		$("#cha").val("");
		$("#dealerMap").show();
		$("#KmFirst").hide();
		$("#nowDealerDiv").hide();
		$("#nowDealerDiv").removeClass("active in");
		 $("#maintainDealerDiv").show();
		 //初始化界面
		 $("#maintainDealerDiv").addClass("active in");
			
			// 选择经销商城市信息取得。
			$.ajax({
				headers: {'Cookie' : document.cookie },
				method : 'get',
				url : rootPath+'/maintain/api/v1/maintainDealerMap?regionType=90011002',
				error:function(XMLHttpRequest, ajaxOptions, thrownError){
					//alert("获取失败!");
				},
				success : function(resultData){

					var wholeHtml = '';
					
					var city = '';
					$.each(resultData,function(maintainDealerMapIndex,maintainDealerMapObj){
						var DealerMapHtml = '';
						var str = maintainDealerMapObj.regionName;
						if(str == "") return;
						var arrRslt = makePy(str);
						var arr = arrRslt[0].substring(0,1);
						for(var i=0;i<26;i++){
							var en = String.fromCharCode((65+i));
							if(arr== en){
								city = maintainDealerMapObj.regionName;
								DealerMapHtml = DealerMapHtml + '<li>'
															  + '<a onclick="selectDealer('+ maintainDealerMapIndex +')">'
															  + '<span style="font-size:18px;color:#7a7a7a">' + city + '</span>'
															  + '<input type="hidden" id="'+maintainDealerMapIndex + '" value="'+ maintainDealerMapObj.regionName +'">'
															  + '</a>'
															  + '</li>'
															  + '<div style="height:1px;margin:0px auto;padding:0px;background-color:#F4F4F4;overflow:hidden;"></div>'
								
								$("#"+en).append(DealerMapHtml);
							}
						}
						
					});

				}
			});		
	}
	//搜索城市
	function searchCity(){
		$("#dealerMap").hide();
		$("#searchCity").html("");
		var regionName = $("#cha").val();
		$.ajax({
			headers: {'Cookie' : document.cookie },
		    type:"GET", 
		    url:rootPath+"/maintain/api/v1/maintainSelectCity?regionName="+regionName, 
		    dataType:"json",      
		    async: false,
		    contentType:"application/json",               
		    data:null, 
		    success:function(data){ 
				var wholeHtml = '<ul class="list-group">';
				
				$.each(data,function(maintainSearchCityIndex,maintainSearchCityObj){
					var DealerMapHtml = '';
					
						DealerMapHtml = DealerMapHtml   + '<li class="list-group-item">'
														+ '<a onclick="selectDealer('+ maintainSearchCityIndex +')">'
														+ '<span style="font-size:18px;color:#7a7a7a">' + maintainSearchCityObj.regionName + '</span>'
														+ '<input type="hidden" id="'+maintainSearchCityIndex + '" value="'+ maintainSearchCityObj.regionName +'">'
														+ '</a>'
														+ '</li>'		
					       wholeHtml += DealerMapHtml;
				});
				wholeHtml = wholeHtml + '</ul>'
				$("#searchCity").append(wholeHtml);
		    },
		    error:function(data){
		    	//alert("数据刷新失败，请联系管理员！");
		    }
		 });
	}
	//搜索经销商
	function searchDealer(){
		$("#list2").hide();
		$("#searchDealer").html("");
		var dealerName = $("#sou").val();
		var regionName = $("#regionName").val();
		$.ajax({
			headers: {'Cookie' : document.cookie },
		    type:"GET", 
		    url:rootPath+"/maintain/api/v1/searchDealer?dealerName="+dealerName, 
		    dataType:"json",      
		    async: false,
		    contentType:"application/json",               
		    data:null, 
		    success:function(data){ 
				var wholeHtml = '<ul class="list-group">';
				var  Km = '';
				$.each(data,function(SearchDealerIndex,SearchDealerObj){
					var DealerMapHtml = '';
					var findDealerHtml = '';
					var lat1 = SearchDealerObj.latitude;
					var lng1 = SearchDealerObj.longitude;
					var lat2 = $("#latitude").val();
					var lng2 = $("#longitude").val();
					Km = GetDistance(lat1,lng1,lat2,lng2).toFixed(2);
					if(lat1==null||lat1=="0"||lng1==null||lng1=="0"){var distance = "暂无";}
					else{var distance = Km + '千米';}
					
						DealerMapHtml = DealerMapHtml   + '<li class="list-group-item">'
														+ '<table style="width:100%" class="table-condensed"><tbody>'
														+ '<tr>'
														+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+SearchDealerIndex+')">'
														+ '<p id="name'+ SearchDealerIndex +'" style="font-family:黑体;font-size:16px;color:#000000">' + SearchDealerObj.dealerName + '</p>'
														+ '<p class="hidden" id="shortName'+SearchDealerIndex+'">'+SearchDealerObj.dealerShortName+'</p>'
														+ '</a></td>'
														+ '<td style="width:100px;text-align:center;font-size:14px;color:#7a7a7a">'
														+ '<span>距离：</span><span>'+ distance + '</span>'
														+ '</td>'
														+ '</tr><tr>'
														+ '<td style="width:160px;text-align:left;">'
														+ '<span id="addr'+ SearchDealerIndex +'" style="font-faminly:宋体;font-size:15px;color:#615f5f">' + SearchDealerObj.detailAddress + '</span>'
														+ '</td>'
														+ '<td style="width:100px;text-align:center;">'
														+ '<a href="tel:'+ SearchDealerObj.serviceHotline +'" id="Tel">'
														+ '<span class="glyphicon glyphicon-earphone" style="color: rgb(255, 0, 23); font-size: 12px;"></span>'
														+ '<span style="font-family:宋体;font-size:14px;color:#7a7a7a"> 电话</span>'
														+ '</a></td>'
														+ '</tr>'
														+ '</tbody></table>'
														+ '<input id="code'+ SearchDealerIndex +'" class="hidden" value="' + SearchDealerObj.dealerCode + '">'
														+ '</li>'
												
						wholeHtml += DealerMapHtml;
				});
				wholeHtml = wholeHtml + '</ul>'
				$("#searchDealer").append(wholeHtml);
		    },
		    error:function(data){
		    	//alert("数据刷新失败，请联系管理员！");
		    }
		 });
	}
	function sure(){
		$("#sure").attr("disabled","disabled");
		$("#sure").attr("class","btnbtn1");
		$("#sure").removeAttr("style");
		window.location = "http://carowner.yonyouauto.com/wx/pub/personal?"+document.cookie;
	}
	
	win.gmcc = {
			"addCarInfo":addCarInfo,
			"next":next,
			"selectNowDealer":selectNowDealer,
			"sureDealer":sureDealer,
			"Sort":Sort,
			"Rad":Rad,
			"GetDistance":GetDistance,
			"selectDealer":selectDealer,
			"selectMaintainDealer":selectMaintainDealer,
			"searchCity":searchCity,
			"searchDealer":searchDealer,
			"sure":sure
			
	}
	
})(window,jQuery)
